package com.founder.helloworldapp;

import java.util.List;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.google.android.maps.MapActivity;

public class TrackMapActivity extends MapActivity {
	
	private TrackMapView mapView;
	
	private ProgressBar loadViewProgressBar;
	
	private DatabaseHelper dbHelper;
	
	private List<Location> locations;
	
	private int maxSize = 500;
	
	private Handler handle;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.track_map_layout);
		loadViewProgressBar = (ProgressBar) findViewById(R.id.progressBar_loadView);
		mapView = (TrackMapView) findViewById(R.id.map_view);
		dbHelper = new DatabaseHelper(this);
		dbHelper.openDb();
		
		handle = new Handler();
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		maxSize = Math.max(dm.widthPixels, dm.heightPixels);
	    long trackId = getIntent().getLongExtra("trackId", 0);
	    
	    loadViewProgressBar.setVisibility(View.VISIBLE);
	    new QueryLocationThread(trackId).start();
	}

	private void notifyMapViewLocations() {
		mapView.setLocations(locations);
	    TrackLineOverlay overlay = new TrackLineOverlay(locations);
	    mapView.getOverlays().add(overlay);
	    loadViewProgressBar.setVisibility(View.INVISIBLE);
	    
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		//如果你的活动显示驾驶方向，这个方法必须返回true，否则，返回false。
		return false;
	}
	
	private class QueryLocationThread extends Thread {
		
		private long trackId;
		
		public QueryLocationThread(long trackId) {
			this.trackId = trackId;
		}
		
		public void run() {
			locations = dbHelper.queryLocations(trackId, maxSize);
			for (Location location : locations) {
				if (dbHelper != null) {
					try {
						location = dbHelper.queryOffsetLocation(location);
					} catch (Exception e) {
						Log.e("TrackMapActivity", "error in queryOffsetLocation.", e);
					}
				}
			}
			if (handle != null) {
				handle.post(updateUI);
			}
		}
	};
	
	//private Handler handle = new Handler();
	
	private final Runnable updateUI = new Runnable() {
		public void run() {
			notifyMapViewLocations();
		}
	};
	

	@Override
	protected void onDestroy() {
		Log.d("hello", "onDestroy is run");
		mapView.getOverlays().clear();
		dbHelper.cleanOffsetCache();
		dbHelper.closeDb();
		dbHelper = null;
		handle = null;
		super.onDestroy();
	}
	


}
